package com.aliyun.oss.utils;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.comm.Protocol;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyuncs.exceptions.ClientException;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;
@Component
public class AliyunOssOperator {
    // 提取常量作为类成员变量，便于维护
    private final String endpoint = "oss-cn-beijing.aliyuncs.com";
    private final String bucketName = "sky-delivery-back-end";
    private final String region = "cn-beijing";
    public String upload(byte[] content,String originalFilename) throws ClientException{

        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        // 设置签名算法版本为 V4
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        // 设置使用 HTTPS 协议访问 OSS，保证传输安全性
        clientBuilderConfiguration.setProtocol(Protocol.HTTPS);
        OSS ossClient= OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider())
                // 设置客户端配置
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();
        String dir= LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM"));
        String newFileName= UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectName=dir+"/"+newFileName;
        ossClient.putObject(bucketName,objectName,new ByteArrayInputStream(content));
        return "https://" +bucketName+"."+endpoint+"/"+objectName;
    }
    /**
     * 根据对象名删除OSS文件
     * @param objectName OSS中的文件对象名（例如：2023/10/xxx.jpg）
     */
    public void deleteByObjectName(String objectName) throws ClientException {
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        clientBuilderConfiguration.setProtocol(Protocol.HTTPS);
        OSS ossClient = null;
        try {
            ossClient = OSSClientBuilder.create()
                    .endpoint(endpoint)
                    .credentialsProvider(CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider())
                    .clientConfiguration(clientBuilderConfiguration)
                    .region(region)
                    .build();
            ossClient.deleteObject(bucketName, objectName);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 根据文件URL删除OSS文件
     * @param fileUrl 上传时返回的文件URL（例如：https://xxx.oss-cn-beijing.aliyuncs.com/2023/10/xxx.jpg）
     */
    public void deleteByUrl(String fileUrl) throws ClientException {
//       解析URL获取objectName
        String prefix = "https://" + bucketName + "." + endpoint + "/";
        if (!fileUrl.startsWith(prefix)) {
            throw new IllegalArgumentException("无效的OSS文件URL: " + fileUrl);
        }
        String objectName = fileUrl.substring(prefix.length());
        deleteByObjectName(objectName);
    }
}
